package com.smartdio.mindtrain.core;

import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Vector;

import com.smartdio.mindtrain.Mind;
import com.smartdio.mindtrain.images.ImageMan;

import cn.icafee.rcp.util.FileUtil;

/**
 * 管理测试题目
 * @author smart
 *
 */
public class TrainMan {
	final private static  int cacheSize = 10;
	
	private ImageMan imgMan ;
	
	private Train current ;
	
	private String currentPath ;
	
	private Vector cache;
	
	private int position = 0;
	
	private String imagesDir = null;
	
	/**
	 * @param imgMan
	 */
	public TrainMan(ImageMan imgMan) {
		super();
		this.imgMan = imgMan;
		cache = new Vector();
		currentPath = System.getProperty("user.dir")+File.separator+"logs";
		File logDir = new File(currentPath);
		if(!logDir.exists()){
			logDir.mkdir();
		}
		
		imagesDir= Mind.getImagePath();
	}


	/**
	 * 建立测试
	 * @param level  测试的等级
	 */
	public void createTest(int level){
		int l = Mind.levels[level];
		
		int size = imgMan.getImageCount();
		
		if(size<l)return ;//如果当前图片不足，不建立训练。
		
		current = new Train();
		current.images = new String[l];
		Random ran = new Random(System.currentTimeMillis());
		
		for(int i=0;i<l;i++){
			int index = ran.nextInt(size);
			current.images[i]=imgMan.getImage(index);
		}
		if(cache.size()>cacheSize){
			cache.remove(0);
		}
		
		cache.add(current);
		position = cache.size();
 	}
	
	
	/**
	 * 把刚刚建立的测试保存到Log文件中
	 */
	public void saveTestLog()throws IOException{
		if(current ==null)return ;
		String fileName = Long.toString(System.currentTimeMillis());
		fileName = currentPath +File.separator+"last.log";
		
		StringBuffer content  = new StringBuffer();
		for (int i = 0 ;i<current.images.length;i++){
			content.append(current.images[i]);
			content.append("\n");
		}
		FileUtil.saveTextFile(fileName, content.toString(), "utf-8");
	}


	/**
	 * @return the current
	 */
	public Train getCurrent() {
		return current;
	}
	
	
	public boolean previous(){
		if(position==1)return false ;
		
		position--;
		current = (Train)cache.get(position-1);
		return true;
	}
	
	public void next(int level){
		if(position<cache.size()){
			position ++;
			current = (Train)cache.get(position-1);
		}
		else{
			createTest(level);
		}
	}

	
	public String getImagesDir(){
		return imagesDir;
	}
}
